package com.qhit.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public @ResponseBody
    Map login(String username, String pwd){
        Subject subject = SecurityUtils.getSubject();
        System.out.println(username);
        UsernamePasswordToken token = new UsernamePasswordToken();
        token.setUsername(username);
        token.setPassword(pwd.toCharArray());
        HashMap<Object, Object> m = new HashMap<>();
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            m.put("msg","账户不存在");
            return m;
        }catch (IncorrectCredentialsException e){
            m.put("msg","mima错误");
            return m;
        }catch (AuthenticationException e){
            e.printStackTrace();
            m.put("msg","认证失败");
            return m;
        }
        if (subject.isAuthenticated()){
            m.put("msg","登录成功");
        }else {
            m.put("msg","失败");
        }
        return m;
    }
    @RequestMapping("/unauthor")
    public String unauthor(){
        return "/unauthor";
    }
}

